<template>
	<view class="page-order">
		<view class="page-order-header">
			<basic-nav-bar 
				backgroundColor="#fff"
				:statusBar="true"
				:border="false" 
				:fixed="true"
				left-icon="arrowleft" 
				title="订单列表" 
				:clickLeftBack="false"
				:showLeftBack="showLeftBack"
				@clickLeft="goBack" 
			/>	
			<orderTabs 
			:tabList="tabList" 
			:current="currentIndex"
			@change="changeTab"  />		
		</view>
		<view class="page-order-content" :style="{'padding-top': headerHeight + 'px'}">
			<view class="page-order-list">
				<swiper class="swiper" :current="currentIndex" @change="swiperChange">
					<template v-for="(tabItem, tabIndex) in orderTabList">
						<swiper-item :key="tabIndex" class="order-list">
							<orderList
							:list="tabItem.list"
							:loading="tabItem.isLoading"
							:isFinished="tabItem.isFinished"
							@loadMore="getData"
							@click:refund="showRefundDetail"
							@click:cancel="goCancel"
							@click:voucher="showVoucher"
							@click:pay="goPay"
							@payTimeout="handlePayTimeout"/>
						</swiper-item>
					</template>
				</swiper>
			</view>
		</view>

		<!-- 小程序首页/订单入口 -->
		<mpEntry page="order"/>			

		<!-- 退款明细 -->
		<uni-popup ref="refundInfo" type="bottom" >
		  <refund-info :refundList="refundList" @close="$refs.refundInfo.close()"></refund-info>
		</uni-popup>

		<!-- 入园凭证 -->
		<uni-popup ref="voucherInfo" type="center" >
          <voucher-info :voucherCodes="voucherInfo">			
		  </voucher-info>
        </uni-popup>
	</view>
</template>
<script>
import sdk from 'sdk'
import {ORDER_STATUS} from '@/model/enum'
import ajax, {getOrderList, cancelOrder, getRefundList, getVoucherInfo} from 'api'
import mpEntry from '@/components/business/mp-entry'
import goPay from 'utils/goPay'
import {isEmpty} from 'utils/helper/validator'
import orderTabs from './components/order-tabs'
import orderList from './components/order-list'
import refundInfo from '@/components/business/refund-info'
import voucherInfo from './components/voucher-info'
import {decodeQueryObject} from 'utils/helper/query'
import store from '@/store'
import setTabBar from '@/mixins/setTabBar'

export default {
	name: 'order',
	components: {
		orderTabs,
		orderList,
		refundInfo,
		voucherInfo,
		mpEntry
	},
	mixins:[setTabBar],
	data() {
		return {
			currentIndex: 0,
			pageSize: 10,
			
			orderTabList: [ // 订单列表
				{id: 1, name:'全部', showCount: false},
				{id: 2, name:'待支付', showCount: true},
				{id: 3, name:'待出行', showCount: true},
				{id: 4, name:'已完成', showCount: false},
				{id: 5, name:'取消/退款', showCount: false}
			].map(tabItem => ({
				...tabItem,
				list: [],
				pageNum: 1, 
				total: 0, 
				isLoading: false,
				isFinished: false
			})),

			refundList: [], // 退款信息
			voucherInfo: {}, // 入园凭证

			headerHeight: 84,
			backToHome: false,
			showLeftBack: true,
		}
	},

	computed: {
		hasLogin() {
			return this.$store.state.login.hasLogin
		},
		tabList() {
			return this.orderTabList.map(orderTab => ({
				id: orderTab.id,
				name: orderTab.name,
				showCount: orderTab.showCount,
				total: orderTab.total
			}))
		}
	},

	watch: {
		hasLogin(val, oldVal) {
			// 登录完重新请求接口
			if(val && !oldVal) {
				this.getData()
			}
		},
		/**
		 * 按理说loadMore会自动触发数据请求，但是LoadMore不稳定，有时候不触发
		 */
		currentIndex(val, oldIndex) {
			if (val !== oldIndex) {
				this.refreshCurTab()
			}
		}
	},

	onShow(){
		this.setTabBarIndex(1)

		// 刷新订单
		this.refreshCurTab()
	},

	onLoad(query) {
		this.getQuery(query)

		const options = decodeQueryObject(query)
		const { mToken } = options
		if(mToken) {
			store.commit('SAVE_TOKEN', { token: mToken })
		} else {
			if (!this.$store.state.login.hasLogin) {
				// console.log('[order index::准备登录]')
				sdk.login({
					notCallLogin: false
				}).then(res => {
					// console.log('[order index::登录成功]')
				})
			} else {
				// console.log('[order index::初始化检测为已登录]')
			}
		}
	},

	mounted() {
		this.initHeaderHeight()
		// #ifdef MP		
		this.showLeftBack = false		
		// #endif
	},
	methods: {
		getQuery(query) {
			// 取消支付跳转到订单列表，则点击返回按钮跳转到首页
			let {payCancelUrl} = decodeQueryObject(query)
			this.backToHome = !!payCancelUrl
		},
		initHeaderHeight() {
			sdk.getOffset('.page-order-header').then(res => {
				this.headerHeight = res.height
			})
		},
		/**
		 * 检查是否在详情页是否操作过订单
		 */
		// checkNeedRefresh() {
		// 	sdk.getSelectCity().then(res => {
		// 		let { needRefresh } = res

		// 		if (needRefresh) {
		// 			this.refreshCurTab()
		// 		}

		// 		sdk.selectCity({ needRefresh: 0 })
		// 	})
		// },
		/**
		 * 刷新当前tab，以更新订单状态
		 */
		refreshCurTab() {
			let curTabList = this.orderTabList[this.currentIndex]

			curTabList.pageNum = 1
			curTabList.isLoading = false
			curTabList.isFinished = false

			this.getData()
		},
		/***
		 * @param {Number} tabIndex tab索引编号，0-4
		 */
		getData(tabIndex) {
			// 未登录，防止登录结束前loadMore再次触发接口请求
			if (!this.$store.state.login.hasLogin) return

			if (typeof tabIndex === 'undefined') {
				tabIndex = this.currentIndex
			}

			if (this.orderTabList[tabIndex].isLoading) return

			this.orderTabList[tabIndex].isLoading = true
			sdk.showLoading({mask: true})

			getOrderList({
				tab: this.orderTabList[tabIndex].id
			}, {
				pageNum: this.orderTabList[tabIndex].pageNum,
				pageSize: this.pageSize
			}).then(res => {
				// 总数
				this.orderTabList[tabIndex].total = res.result.total

				// 待支付的订单数
				if (!isEmpty(res.result.initializerOrderNum)) {
					this.orderTabList[1].total = res.result.initializerOrderNum
				}

				// 待出行的订单数
				if (!isEmpty(res.result.waitingTravelOrderNum)) {
					this.orderTabList[2].total = res.result.waitingTravelOrderNum
				}

				if (this.orderTabList[tabIndex].pageNum <= 1) {
					this.orderTabList[tabIndex].list = res.result.list || []
				} else {
					this.orderTabList[tabIndex].list.push.apply(this.orderTabList[tabIndex].list, res.result.list || [])
				}

				// 检查是否加载完毕
				if (this.orderTabList[tabIndex].pageNum >= res.result.pages) {
					this.orderTabList[tabIndex].isFinished = true
				}

				this.orderTabList[tabIndex].pageNum++

				this.orderTabList[tabIndex].isLoading = false

				sdk.hideLoading()
			}).catch(_ => {
				sdk.hideLoading()
				this.orderTabList[tabIndex].isLoading = false
			})
		},
		
		// 显示入园凭证
		showVoucher(orderItem) {
			sdk.showLoading({mask: true})
			getVoucherInfo({orderNo: orderItem.orderNo})
			.then(res => {
				if (res && res.result && res.result.codes) {
					this.voucherInfo = res.result.codes || [];
					this.$refs.voucherInfo.open()
					sdk.hideLoading()
				} else {
					sdk.showToast({
						icon: 'none',
						title: '抱歉，暂无入园凭证'
					})
				}
			})
			.catch(_ => {
				sdk.hideLoading()
			})
		},
		// 显示退款明细
		showRefundDetail(orderItem) {
			// TODO 错误提示
			sdk.showLoading({mask: true})
			getRefundList({orderNo: orderItem.orderNo})
			.then(res => {
				if (res && res.result && res.result.length) {
					this.refundList = res.result || [];
					this.$refs.refundInfo.open()

					sdk.hideLoading()
				} else {
					sdk.showToast({
						icon: 'none',
						title: '暂无退款信息'
					})
				}
			})
			.catch(_ => {
				sdk.hideLoading()
			})
		},
		// 取消订单，跳转到取消订单页面
		goCancel(orderItem) {

			// // 不管是否支付，都要跳转到退款页面
			// sdk.navigateTo({
			// 	url: `/ubd/trade/detail/refundApply?orderNo=${orderItem.orderNo}`
			// })
			
			let {COMFIRMING, SUCCEED} = ORDER_STATUS

			if ([COMFIRMING, SUCCEED].includes(Number(orderItem.orderStatus))) { // 可退款
				// 判断是否可以取消订单
				sdk.navigateTo({
					// url: `/ubd/trade/detail/refundApply?orderNo=${orderItem.orderNo}`
					url: `/packageOrder/pages/refund/index?orderNo=${orderItem.orderNo}`
				})
			} else { // 无退款，直接取消
				sdk.showLoading({mask: true})
				cancelOrder({orderNo: orderItem.orderNo}).then(res => {
					sdk.hideLoading()
					sdk.showToast({
						title: '取消成功'
					})

					// 更新订单列表
					setTimeout(() => {
						this.refreshCurTab()
					}, 1500)
				}).catch(_ => {
					sdk.showToast({
						icon: 'none',
						title: '取消失败'
					})
				})
			}
		},
		// 跳转支付
		async goPay(orderItem) {
			const { orderNo } = orderItem
			sdk.showLoading({mask: true})
			await goPay(orderNo, 'navigate')
			sdk.hideLoading()
		},
		// 支付超时 doNothing
		handlePayTimeout(orderItem) {

		},
		goBack() {
			if (this.backToHome) {
				sdk.gotoHomePage()
			} else {
				sdk.navigateBack() 
			}
		},
		changeTab(index) {
			this.currentIndex = index
		},
		swiperChange(e){
			this.changeTab(e.detail.current)
		}
	}
}
</script>
<style lang="less">
.page-order{
	background: #F6F9FD;
	height: 100vh;
	display: flex;
	flex-direction: column;
	.page-order-header{
		position: fixed;
		left:0;
		top:0;
		right:0;
		z-index: 999;
	}
	.page-order-content{
		background: #F6F9FD;
		padding-top: 168rpx;
		height: 100%;
		box-sizing: border-box;
		.page-order-list{
			padding: 20rpx @page_horizonal_margin;
			box-sizing: border-box;
			height: 100%;	
			.swiper{
				height: 100%;
			}
		}
	}
}
</style>